<script setup lang="ts">
import { computed, watch, onMounted } from 'vue';
import { useTimelineStore, type TimelineItem } from '../stores/timeline';
import { registerAction } from '../assets/hotkeys.js';
import { commandService } from '../services/commandService';
import { useI18n } from 'vue-i18n';
import { openContextMenu, registerSubmenu } from '../assets/menus.js';
import { useMenuStore } from '../stores/menu';
import { Icon } from '@iconify/vue';

const props = defineProps<{ uri?: string }>();
const tl = useTimelineStore();
const menuStore = useMenuStore();
const { t } = useI18n();

onMounted(async () => {
  if (props.uri) {
    await tl.loadTimeline(props.uri);
  }
});
watch(() => props.uri, async (v: string | undefined) => { if (v) await tl.loadTimeline(v); });

const grouped = computed(() => {
  const byDate: Record<string, TimelineItem[]> = {};
  for (const item of tl.items) {
    const dateKey = new Date(item.timestamp).toDateString();
    if (!byDate[dateKey]) byDate[dateKey] = [];
    byDate[dateKey].push(item);
  }
  return Object.entries(byDate).map(([date, items]) => ({ date, items }));
});

function onItemClick(it: TimelineItem) {
  // 默认行为：触发命令或打开
  if (it.command?.action) {
    const act = String(it.command.action);
    if (act === 'restore') {
      commandService.execute('timeline.restore', it.command.args || {});
    } else if (act === 'diff') {
      commandService.execute('timeline.diff', it.command.args || {});
    } else if (act === 'open') {
      commandService.execute('file:openPath', it.command.args || { uri: it.resourceUri });
    }
  } else {
    try {
      commandService.execute('file:openPath', { uri: it.resourceUri });
    } catch (e) {
      commandService.execute('timeline.open', { uri: it.resourceUri });
    }
  }
}

function onItemRightClick(event: MouseEvent, item: TimelineItem) {
  event.preventDefault();
  const at = { x: event.clientX, y: event.clientY };
  const ctx = { item, t };
  openContextMenu({ use: 'timeline.item.context' }, at, ctx);
}

onMounted(() => {
  // 注册时间线项右键菜单（可复用）
  registerSubmenu('timeline.item.context', (ctx: { item?: TimelineItem; t?: any }) => {
    const it = ctx?.item;
    const tr = ctx?.t || ((k: string) => k);
    if (!it) return [];
    return [
      { id: 'timeline.open', label: tr('timeline.open') || 'Open', action: 'timeline:open' },
      { id: 'sep1', label: '-' },
      { id: 'timeline.restore', label: tr('timeline.restore') || 'Restore', action: 'timeline:restore' },
      { id: 'timeline.diff', label: tr('timeline.diff') || 'Diff', action: 'timeline:diff' },
    ];
  });

  // 注册动作，从菜单 store 获取当前上下文
  registerAction('timeline:open', (_evt?: any) => {
    const currentCtx = menuStore.context;
    const targetItem = currentCtx?.item || tl.items[0];
    if (targetItem) {
      try {
        commandService.execute('file:openPath', { uri: targetItem.resourceUri });
      } catch (e) {
        commandService.execute('timeline.open', { uri: targetItem.resourceUri });
      }
    }
  });

  registerAction('timeline:restore', (_evt?: any) => {
    const currentCtx = menuStore.context;
    const targetItem = currentCtx?.item || tl.items[0];
    if (targetItem) {
      commandService.execute('timeline.restore', {
        resourceUri: targetItem.resourceUri,
        id: targetItem.id,
        source: targetItem.source,
      });
    }
  });

  registerAction('timeline:diff', (_evt?: any) => {
    const currentCtx = menuStore.context;
    const targetItem = currentCtx?.item || tl.items[0];
    if (targetItem) {
      commandService.execute('timeline.diff', {
        resourceUri: targetItem.resourceUri,
        id: targetItem.id,
        source: targetItem.source,
      });
    }
  });
});
</script>

<template>
  <div class="flex h-full min-h-0 flex-col">
    <!-- Toolbar: filter sources -->
    <div class="flex items-center gap-2 px-2 py-1 border-b dark:border-neutral-800">
      <div class="text-xs text-slate-500 dark:text-neutral-400">{{ t('timeline.title') }}</div>
      <div class="flex-1"></div>
    </div>

    <!-- Content -->
    <div class="flex-1 min-h-0 overflow-auto thin-scrollbar p-2">
      <div v-if="tl.loading" class="text-xs text-slate-400 dark:text-neutral-500 px-2 py-1">{{ t('timeline.loading') }}</div>
      <div v-else-if="!grouped.length" class="text-xs text-slate-400 dark:text-neutral-500 px-2 py-1">{{ t('timeline.no_entries') }}</div>
      <div v-else class="flex flex-col gap-3">
        <div v-for="g in grouped" :key="g.date" class="flex flex-col gap-1">
          <div class="text-[11px] font-medium text-slate-500 dark:text-neutral-400">{{ g.date }}</div>
          <div class="flex flex-col">
            <div v-for="it in g.items" :key="it.id" class="flex items-center gap-2 px-2 py-1 rounded hover:bg-slate-100 dark:hover:bg-neutral-800 cursor-pointer select-none" @dblclick="onItemClick(it)" @contextmenu="onItemRightClick($event, it)">
              <Icon :icon="it.iconClass || 'codicon:history'" width="14" height="14" class="text-slate-500 dark:text-neutral-400" />
              <div class="flex-1 min-w-0">
                <div class="text-xs truncate">{{ it.message }}</div>
              </div>
              <div class="text-[11px] text-slate-400 dark:text-neutral-500">{{ new Date(it.timestamp).toLocaleTimeString() }}</div>
              <div class="text-[10px] text-slate-400 dark:text-neutral-500 ml-2">{{ it.source }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.thin-scrollbar::-webkit-scrollbar { width: 8px; height: 8px; }
html:not(.dark) .thin-scrollbar::-webkit-scrollbar-thumb { background-color: rgba(100,116,139,.55); border-radius: 8px; border: 2px solid transparent; background-clip: padding-box; }
html.dark .thin-scrollbar::-webkit-scrollbar-thumb { background-color: rgba(148,163,184,.45); border-radius: 8px; border: 2px solid transparent; background-clip: padding-box; }
</style>